package revontuli.aMHD;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class UserLocationSvc extends Service {
	private static StopFinder MAIN_ACTIVITY;
	private Timer timer = new Timer();
	private static long UPDATE_INTERVAL = 1*10*1000;
	private static long DELAY_INTERVAL = 0;
	private Location lastLocation;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	@Override
	public void onDestroy() {
		stopService();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
    	startService();
		return START_STICKY;
	}
	
	public static void setMainActivity(StopFinder activity) {
		MAIN_ACTIVITY = activity;
	}
	
	private void startService() {
		Toast.makeText(MAIN_ACTIVITY.getApplicationContext(), "startservice", Toast.LENGTH_SHORT).show();
		TimerTask timerTask = new TimerTask() {
			public void run() {
				try {
					getNewLocation();
					Thread.sleep(UPDATE_INTERVAL);
				} catch(InterruptedException e) {
					Log.e("chyba", e.getMessage(), e);
				} catch(Exception e) {
					Log.e("chyba", e.getMessage(), e);
				}
				
			}
		};
		
		timer.scheduleAtFixedRate(timerTask, DELAY_INTERVAL, UPDATE_INTERVAL);
	}
	
	private void getNewLocation() {
//		Toast.makeText(MAIN_ACTIVITY.getApplicationContext(), "startservice", Toast.LENGTH_SHORT).show();
		lastLocation = null;
	}
	
	private void stopService() {
		Toast.makeText(MAIN_ACTIVITY.getApplicationContext(), "stopservice", Toast.LENGTH_SHORT).show();
		if (timer != null) {
			timer.cancel();
		}
	}
}